<template>
  <div>
    <!-- 编辑事件按钮 -->
    <el-button link type="primary" :icon="Edit" @click="openDialog">编辑事件</el-button>

    <!-- 事件编辑弹窗 -->
    <el-dialog :title="eventName + ' 事件'" v-model="dialogVisible" width="70%" @close="resetEvent">
      <CodeEditor v-model="eventData" class="js-edit" :placeholder="placeholderText" />
      <!-- 弹窗底部操作 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEvent">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import CodeEditor from '@/components/designer/config-group/CodeEditor.vue';

const props = defineProps({
  config: {
    type: Object,
    required: true
  },
  eventName: {
    type: String,
    default: ''
  }
});

const placeholderText = ref('请输入对应事件触发后执行的JavaScript代码')

const dialogVisible = ref(false);
const eventData = ref('');

// 打开弹窗时加载已有事件内容
const openDialog = () => {
  // 保证 events 存在
  if (!props.config.events) {
    props.config.events = {};
  }
  eventData.value = props.config.events[props.eventName] || '';
  dialogVisible.value = true;
};

// 保存编辑后的事件内容
const saveEvent = () => {
  props.config.events[props.eventName] = eventData.value;
  dialogVisible.value = false;
};

// 重置内容（关闭时不保存）
const resetEvent = () => {
  eventData.value = props.config.events?.[props.eventName] || '';
};

// 若 config.id 或 eventName 变动，重新同步事件内容（确保编辑器内容正确）
watch(
  [() => props.config.id, () => props.eventName],
  () => {
    eventData.value = props.config.events?.[props.eventName] || '';
  },
  { immediate: true }
);
</script>

<style scoped>
.js-edit {
  height: 50vh;
}
</style>